package jiang;

public class Repository {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(new Consumer("c1", t), "c1");
        Thread t2 = new Thread(new Consumer("c2", t), "c2");
        Thread t3 = new Thread(new Consumer("c3", t), "c3");
        Thread t4 = new Thread(new Provider("t1", t), "t1");
        Thread t5 = new Thread(new Provider("t2", t), "t2");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

class Ticket {
    private int num = 0;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public synchronized void consume() {
        if (num > 0) {
            num--;
            System.out.println(Thread.currentThread().getName() + " 减少 " + num);
            notifyAll();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public synchronized void provide() {
        if (num < 100) {
            num++;
            System.out.println(Thread.currentThread().getName() + " 增加 " + num);
            notifyAll();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {

    String name;
    Ticket t;

    public Consumer(String name, Ticket t) {
        this.name = name;
        this.t = t;
    }

    @Override
    public void run() {
        while (true) {
            t.consume();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

class Provider implements Runnable {

    String name;
    Ticket t;

    public Provider(String name, Ticket t) {
        this.name = name;
        this.t = t;
    }

    @Override
    public void run() {
        while (true) {
            t.provide();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}